package com.als.healthymananger.controller.impl;

import com.als.healthymananger.controller.LoginApi;
import com.als.healthymananger.entity.Token;
import com.als.healthymananger.entity.User;
import com.als.healthymananger.service.LoginService;
import com.als.healthymananger.service.TokenService;
import com.als.healthymananger.service.UsersService;
import com.als.healthymananger.utils.Encoder;
import com.als.healthymananger.utils.RespBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/login")
public class LoginController implements LoginApi {
    @Autowired
    private UsersService usersService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private Encoder encoder;
    @Autowired
    private TokenService tokenService;


    @Value("${jwt.token-header}")
    private String tokenHeader;
    @Value("${jwt.token-head}")
    private String tokenHead;

    @Override
    public RespBean signIn(String username, String password, boolean remember, String authorization) {
        // 判断authorization是否存在， 存在则用jwt登录，否则用用户名、密码登录
        if (authorization != null) {
            // 获取jwt
            String jwt = authorization.substring(tokenHead.length() + 1);
            Token token = tokenService.getOne(new QueryWrapper<Token>().eq("jwt", jwt));

            // 判断jwt是否过期
            if (loginService.loginExpired(token))
                return RespBean.badRequest("jwt已过期");

            User user = usersService.getById(token.getUsername());

            // 登录次数+1
            user.setCount(user.getCount()+1);
            usersService.updateById(user);

            //生成jwt
            String jwt2 = loginService.createJWT(user.getUsername(), user.getType());
            // 更新token
            token.setJwt(jwt2);
            tokenService.updateById(token);

            Map<String, Object> map = new HashMap<>();
            map.put("tokenHeader", tokenHeader);
            map.put("tokenHead", tokenHead);
            map.put("jwt", jwt2);

            return RespBean.ok("登录成功", map);
        } else {
            // 验证密码、用户名是否符合规范
            if (!loginService.validate(username, password))
                return RespBean.badRequest("密码、用户名不符合规范");

            // 通过用户名和密码从数据库中获取user；
            User user = usersService.getOne(new QueryWrapper<User>().eq("username", username).eq("password", encoder.encode(password)));
            if (user == null)
                return RespBean.badRequest("用户名或密码不正确");

            // 登录次数+1
            user.setCount(user.getCount()+1);
            usersService.updateById(user);

            //生成jwt
            String jwt = loginService.createJWT(user.getUsername(), user.getType());

            if (remember){
                Token token = new Token();
                token.setJwt(jwt);
                token.setUsername(username);
                tokenService.save(token);
            }

            Map<String, Object> map = new HashMap<>();
            map.put("tokenHeader", tokenHeader);
            map.put("tokenHead", tokenHead);
            map.put("jwt", jwt);

            return RespBean.ok("登录成功", map);
        }
    }

    @Override
    public RespBean signUp(String username, String password, String userType) {
        // 判断username是否已存在
        if (usersService.getById(username) != null)
            return RespBean.badRequest("用户名已存在");

        // 验证密码、用户名是否符合规范
        if (!loginService.validate(username, password))
            return RespBean.badRequest("密码、用户名不符合规范");

        // userType只能是mananger、master、member三个值中的一个
        if (!(userType.equals("mananger") || userType.equals("master") || userType.equals("member")))
            return RespBean.badRequest("userType只能是mananger或master或member");

        User user = loginService.createUser(username, password, userType);
        if (user != null)
            return RespBean.ok("注册成功", user);
        else
            return RespBean.badRequest("注册失败");
    }


    @Override
    public RespBean signOut(String authorization) {
        String jwt = authorization.substring(tokenHead.length()+1);

        return tokenService.remove(new QueryWrapper<Token>().eq("jwt", jwt))? RespBean.ok("注销成功"): RespBean.badRequest("注销失败");
    }

    @Override
    public RespBean forget(String username, String name, String password) {
        User user = usersService.getOne(new QueryWrapper<User>().eq("username", username).eq("name", name));
        if (user == null)
            return RespBean.badRequest("用户名或密码错误");

        if (!loginService.validate(username, password))
            return RespBean.badRequest("用户名或密码不满足要求");

        return usersService.updateById(user)? RespBean.ok("更换密码成功"): RespBean.badRequest("更换密码失败");
    }
}
